package com.esd.chyl.controller;

import com.esd.chyl.model.KnowledgeStatistics;
import com.esd.chyl.service.KnowledgeStatisticsService;
import com.esd.chyl.util.ReturnResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class KnowledgeStatisticsController {

    private static Logger logger = LoggerFactory.getLogger(KnowledgeStatisticsController.class);

    @Autowired
    private KnowledgeStatisticsService service;

    @GetMapping("/form")
    public ModelAndView form(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("form");
        List<KnowledgeStatistics> all = service.getAll(null);
        if(all == null || all.size() == 0){
            mv.addObject("entity", new KnowledgeStatistics());
        }else{
            mv.addObject("entity", all.get(0));
        }
        return mv;
    }

    @PostMapping("/knowledgeInfo")
    @ResponseBody
    public Map<String, Object> getInfo(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("form");
        List<KnowledgeStatistics> all = service.getAll(null);
        KnowledgeStatistics entity = new KnowledgeStatistics();
        if(all != null && all.size() > 0){
            entity = all.get(0);
        }
        List<Integer> list = new ArrayList<>();
        list.add(Integer.valueOf(entity.getZlq()));
        list.add(Integer.valueOf(entity.getZzq()));
        list.add(Integer.valueOf(entity.getLw()));
        list.add(Integer.valueOf(entity.getSbq()));
        list.add(Integer.valueOf(entity.getOthers()));
        return ReturnResult.storeData(list);
    }

    @PostMapping("/list")
    @ResponseBody
    public Map<String, Object> getList(){
        List<KnowledgeStatistics> all = service.getAll(null);
        if(all == null || all.size() == 0){
            return ReturnResult.storeData(new KnowledgeStatistics());
        }
        return ReturnResult.storeData(all.get(0));
    }

    @PostMapping("/saveOrUpdate")
    @ResponseBody
    public Map<String, Object> saveOrUpdate(KnowledgeStatistics param){
        if(StringUtils.isBlank(param.getId())){
            if(!service.insert(param)){
                return ReturnResult.fail();
            }
        }else{
            if(!service.update(param)){
                return ReturnResult.fail();
            }
        }
        return ReturnResult.success();
    }
}


